# -*- coding: utf-8 -*-
# @Time: 2022/4/28 13:47
# @Author: 发抖的小喵喵
# @Email: panyi_20210601@163.com
# @File: getSign.py
# @Project: haixin
# @Software: PyCharm


import json
import time
import random
import uuid
import hashlib


class GetSign:

    def __init__(self, data):
        self.data = data

    def get_now_time(self):
        """
        获取当前时间的时间戳
        :return:
        """
        # self.timestamp = str(round(time.time() * 1000))
        timestamp = str(int(time.time() * 1000))
        # print(timestamp)
        return timestamp

    def get_random_num20(self):
        """
        时间和随机数拼接20位字符串
        :return:
        """
        now = self.get_now_time()
        random_num = str(now) + "%07d" % random.randint(0, 1000000)
        # print(random_num)
        return random_num

    def get_uuid(self):
        """
        获取随机字符串
        :return:
        """
        randNum = str(uuid.uuid1().hex)  # hex去掉中间的“-”
        # print(randNum)
        return randNum

    def md5(self, string):
        """
        获取加密sign
        :param string: 将要加密的字符串
        :return:
        """
        hl = hashlib.md5()  # 调用MD5方法创建对象
        hl.update(string.encode("utf-8"))  # 将string字串加密，默认小写
        sign = (hl.hexdigest()).upper()  # 转换成16进制大写加密字符串
        return sign

    def sign(self):
        timestamp = self.get_now_time()
        randNum = self.get_uuid()
        _list = []
        headers = {
            "appId": "1a748b70d0cb4a8a8e37e959f4a4f1e6",  # 海信
            # "appId": "ee814c0af5d460082c77a2cd50c3e9b",  # 乐趣 接口已删
            "timestamp": timestamp,
            "randNum": randNum,
            "appSecret": "0c128efdc2ef45c1a7be39462701e65b"  # 海信
            # "appSecret": "decea1239f4c4550a10e405fadb2c672"   # 乐趣 接口已删
        }

        for i in headers.items():
            # print(i)
            _list.append("=".join(i))
            # print(_list)

        # separators键值对之间默认的就是(',',':')。sort_keys排序
        body_dict = json.dumps(self.data)
        _list.append("body=" + body_dict)
        _list.sort()
        md5_param = "&".join(_list)
        # print(md5_param)
        sign = self.md5(md5_param)
        # print("sign：" + sign + "\n", "body：" + body_dict + "\n" + timestamp + "\n" + randNum)
        return sign, body_dict, timestamp, randNum


if __name__ == "__main__":
    # postman，get请求，需将参数拼接在url上，然后body也以json格式传参
    # json传参时，直接复制control里的参数，使用beautify美化格式会报sign错误
    # param = {
    #     "userMobile": "13817108474"
    # }
    param = {
        "shopId": "80101",
        "userMobile": "13000000013"
    }

    GetSign(param).sign()
